package com.dongwu.manager.web;

import com.dongwu.common.dto.Result;
import com.dongwu.common.utils.Exceptions;
import com.dongwu.common.utils.UserUtils;
import com.dongwu.common.web.BaseController;
import com.dongwu.common.web.Servlets;
import com.dongwu.manager.entity.AppTemplate;
import com.dongwu.manager.entity.TemplateType;
import com.dongwu.manager.service.AppTemplateService;
import com.dongwu.manager.service.TemplateTypeService;
import com.dongwu.security.entity.User;
import com.dongwu.security.service.IUserService;
import com.dongwu.security.utils.SecurityUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 营销工具
 * @author xyj
 *
 */
@Controller
@RequestMapping("/manager/appTemplate")
public class AppTemplateController extends BaseController<AppTemplate, String> {

    @Autowired
    private AppTemplateService appTemplateService;

    @Autowired
    private IUserService userService;

    @Autowired
    private TemplateTypeService templateTypeService;

    @RequestMapping(value = "/queryTree")
    @ResponseBody
    public Result queryTree(HttpServletRequest request) {

        try {
            User user = userService.findByLoginName(UserUtils.getUserLoginName());
            List<Map<String, Object>> nodes = Lists.newArrayList();
            Map<String, Object> searchParams = Servlets
                    .getParametersStartingWith(request, SEARCH_PARAM_PREFIX);
            if(searchParams.get("EQ_showType")!= ""){
                Integer showType = Integer.parseInt(searchParams.get("EQ_showType").toString());
                AppTemplate appTemplate = appTemplateService.findByShowTypeAndIsDefault(showType,true);
                Iterable<AppTemplate> appTemplates = appTemplateService.findByStatusAndShowType(showType);
                if(appTemplate != null && !"admin".equals(user.getLoginName())){
                    getAppTemplate(appTemplate, nodes);
                }
                for (Iterator<AppTemplate> iter = appTemplates.iterator(); iter.hasNext();) {
                    getAppTemplate((AppTemplate) iter.next(), nodes);
                }
            }
            return Result.successResult(nodes);
        } catch (Exception e) {
            String msg = Exceptions.getMessage(e);
            logger.error(msg, e);
            return Result.errorResult(msg);
        }

    }

    private void getAppTemplate(AppTemplate appTemplate, List<Map<String, Object>> nodes) {
        Map<String, Object> appTemplateData = Maps.newHashMap();
        appTemplateData.put("tId", appTemplate.getId());
        appTemplateData.put("id", appTemplate.getId());
        appTemplateData.put("name", appTemplate.getName());
        nodes.add(appTemplateData);
    }

    /**
     * 新增
     * @param appTemplate
     * @return
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public Result save(AppTemplate appTemplate) {
        try {
//            if (appTemplate.getUser() == null) {
//                appTemplate.setUser(userService.findByLoginName(UserUtils.getUserLoginName()));
//            }
            if (!SecurityUtils.hasRole(this.getAddRole())) {
                return Result.denyResult();
            }

            appTemplate.setDefault(false);
            baseService.save(appTemplate);
            return Result.successResult();

        } catch (Exception e) {
            String msg = Exceptions.getMessage(e);
            logger.error(msg, e);
            return Result.errorResult(msg);
        }
    }

    @RequestMapping(value = "/add")
    public String add(ModelMap model) {

        User user = userService.findByLoginName(UserUtils.getUserLoginName());
        List<TemplateType> templateTypes = new ArrayList<>();
        if("admin".equals(user.getLoginName())){
            templateTypes = templateTypeService.findAll();
        }else{
            if(user.getUserTemplateTypes().size() > 0){
                templateTypes = templateTypeService.findList(user.getUserTemplateTypes());
            }
        }
        model.addAttribute("templateTypes", templateTypes);
        return super.add(model);

    }

    @ResponseBody
    public Result get(@PathVariable("id") String id) {
        try {
            if (!SecurityUtils.hasRole(this.getQueryRole())) {
                return Result.denyResult();
            }
            User user = userService.findByLoginName(UserUtils.getUserLoginName());
            AppTemplate appTemplate = baseService.get(id);
            List list = new ArrayList();
            list.add(appTemplate);
            List<TemplateType> templateTypes = new ArrayList<>();
            if("admin".equals(user.getLoginName())){
                templateTypes = templateTypeService.findAll();
            }else{
                if(user.getUserTemplateTypes().size() > 0){
                    templateTypes = templateTypeService.findList(user.getUserTemplateTypes());
                }
            }
            list.add(templateTypes);
            return Result.successResult(list);
        } catch (Exception e) {
            String msg = Exceptions.getMessage(e);
            logger.error(msg, e);
            return Result.errorResult(msg);
        }
    }

    @RequestMapping(value = "/getTemplateType")
    @ResponseBody
    public Result getTemplateType() {
        User user = userService.findByLoginName(UserUtils.getUserLoginName());
        List<TemplateType> templateTypes = new ArrayList<>();
        if("admin".equals(user.getLoginName())){
            templateTypes = templateTypeService.findAll();
        }else{
            if(user.getUserTemplateTypes().size() > 0){
                templateTypes = templateTypeService.findList(user.getUserTemplateTypes());
            }
        }

        return Result.successResult(templateTypes);
    }


}
